#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
  public:
    ListNode* reverseList(ListNode* head) {
        ListNode* curr = head;
        ListNode* prev = nullptr;
        while (curr) {
            ListNode* next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        head1 = reverseList(head1);
        head2 = reverseList(head2);
        int remain = 0;
        ListNode* res = new ListNode(0);
        ListNode* tail = res;
        ListNode* cur1 = head1;
        ListNode* cur2 = head2;
        while (cur1 || cur2 || remain) {
            if (cur1) {
                remain += cur1->val;
                cur1 = cur1->next;
            }
            if (cur2) {
                remain += cur2->val;
                cur2 = cur2->next;
            }
            tail = tail->next = new ListNode(remain % 10);
            remain /= 10;
        }
        return reverseList(res->next);
    }
};